package com.weiaibenpao.demo.chislim.ui;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.jaeger.library.StatusBarUtil;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;
import com.weiaibenpao.demo.chislim.Interface.OnGetPro;
import com.weiaibenpao.demo.chislim.LocationUtil;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.RunningPreferences;
import com.weiaibenpao.demo.chislim.RunningService;
import com.weiaibenpao.demo.chislim.bean.UserBean;
import com.weiaibenpao.demo.chislim.hurui.activity.HBaseActivity;
import com.weiaibenpao.demo.chislim.update.UpdateManager;
import com.weiaibenpao.demo.chislim.util.Default;
import com.weiaibenpao.demo.chislim.util.StackManager;
import com.weiaibenpao.demo.chislim.util.Utils;
import com.weiaibenpao.demo.chislim.util.WriteReadSharedPrefs;

import static com.weiaibenpao.demo.chislim.sport.utils.Constant.MARATHON_DISTANCE;
import static com.weiaibenpao.demo.chislim.sport.utils.Constant.MARATHON_ID;
import static com.weiaibenpao.demo.chislim.sport.utils.Constant.MARATHON_TITLE;
import static com.weiaibenpao.demo.chislim.util.Default.REQUEST_PERMISSION_CODE;

public class MainActivity extends HBaseActivity implements View.OnClickListener,OnGetPro {
    private StackManager manager = new StackManager();
    private UserBean user;
    private LocationUtil mLocationUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        checkPermission();
        StatusBarUtil.setColor(this , getResources().getColor(R.color.blackbg ) , 0);
        user = UserBean.getUserBean();
        initView();
        if(Utils.isNetWorkConnected()) {
            new UpdateManager(this).checkUpdate();     //监测更新
        }else {
            Toast.makeText(this, "亲，网络连了么？", Toast.LENGTH_LONG).show();
        }
        manager.pushActivity(MainActivity.this);
        initLocation();
    }

    private void initLocation() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { //用户授予了定位权限
            mLocationUtil = new LocationUtil(this);
            mLocationUtil.startLocation();
        }
    }

    FragmentTabHost tabHost;
    private void initView(){
        //读取用户信息到单例中
        WriteReadSharedPrefs.readUser(this.getApplicationContext(),user);
        tabHost= (FragmentTabHost) findViewById(android.R.id.tabhost);
        tabHost.setup(this,getSupportFragmentManager(),R.id.content);
        initTabs();
    }

    private void initTabs(){
        MainTab[] tabs = MainTab.values();
        final int size = tabs.length;

        for (int i=0;i<size ;i++){
            MainTab mainTab=tabs[i];
            TabHost.TabSpec tab=tabHost.newTabSpec(getString(mainTab.getResName()));
            View indication= LayoutInflater.from(this).inflate(R.layout.tab_indication,null);
            TextView textView= (TextView) indication.findViewById(R.id.tab_title);
            textView.setText(mainTab.getResName());
         //   textView.setTextColor(getResources().getColor(R.color.blue_bg));
            Drawable drawable= ContextCompat.getDrawable(this,mainTab.getResIcon());
            textView.setCompoundDrawablesWithIntrinsicBounds(null, drawable,null,null);
            tab.setIndicator(indication);
            tabHost.addTab(tab,mainTab.getClz(),null);
            tabHost.getTabWidget().setDividerDrawable(null);//去掉竖直分割线
        }
    }

    @Override
    public void onClick(View view) {

    }


    @Override
    public void getPro(int pro) {

    }



    /**
     * 分享回调
     */
    @Override
    public void shareSport(String text,String title,String url,String media) {
        /*目前支持文本、图片（本地及URL）、音频及视频URL的分享,要分享图片的URL*/
        UMImage image = new UMImage(this, media);
        final SHARE_MEDIA[] displaylist = new SHARE_MEDIA[]
                {
                        SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE,SHARE_MEDIA.SINA,
                        SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE
                };
        new ShareAction(this).setDisplayList( displaylist )
                .withText( text )
                .withTitle(title)
                .withTargetUrl(url)
                .withMedia(image)
                .setListenerList(umShareListener)
                .open();
    }

    /**
     *  分享回调
     */
    private UMShareListener umShareListener = new UMShareListener(){
        @Override
        public void onResult(SHARE_MEDIA platform) {
            Log.i("分享","-------------成功-----------");
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            //Toast.makeText(context,platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Log.i("分享","-------------取消-----------");
        }
    };

    /**
     * 分享面板添加按钮的回调
     */
    private ShareBoardlistener shareBoardlistener = new  ShareBoardlistener() {

        @Override
        public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
            if (share_media==null){
                if (snsPlatform.mKeyword.equals("11")){
                    Log.i("分享面板添加按钮的回调","-------------add button success-----------");
                }
            }
            else {
                new ShareAction(MainActivity.this).setPlatform(share_media).setCallback(umShareListener)
                        .withText("多平台分享")
                        .share();
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this.getApplicationContext()).onActivityResult( requestCode, resultCode, data);
    }


    Handler mHandler = new Handler();
    @Override
    protected void onResume() {
        super.onResume();
        //在Handler 的run()里面或者新开线程的run里面打印的getClass的getSimpleName和getCanonicalName都为空，
        // 因为getClass属于Object的final方法，此时不是执行最外层的MainActivity的
        //所以这里在外层调用getClass().getCanonicalName()
        int state = RunningPreferences.getInstance().getRunningState();
        if(RunningService.RUNNING == state || RunningService.PAUSE == state){
            final String canonicalName = getClass().getCanonicalName();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                   if(Utils.isActivityForeground(canonicalName)) {
                       String runningActivity = RunningPreferences.getInstance().getRunningActivity();
                       Log.e("MainActivity", " runningActivity is " + runningActivity);
                       if (!TextUtils.isEmpty(runningActivity)) {
                           Intent intent = new Intent(runningActivity);
                           if(RunningPreferences.getInstance().getBoolean(RunningPreferences.IS_PERSONAL_MARATHON)){
                               intent.putExtra(MARATHON_DISTANCE, RunningPreferences.getInstance().getString(MARATHON_DISTANCE));
                               intent.putExtra(MARATHON_TITLE, RunningPreferences.getInstance().getString(MARATHON_TITLE));
                               intent.putExtra(MARATHON_ID, RunningPreferences.getInstance().getString(MARATHON_ID));
                           }
                           startActivity(intent);
                       }
                   }
                }
            },150);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mHandler !=null){
            mHandler.removeCallbacksAndMessages(null);
        }
        if(mLocationUtil != null) mLocationUtil.destroyLocation();

    }

    /**
     * 权限检查
     * @param
     */
    public void checkPermission(){
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, Default.MUST_PERMISSIONS,
                    REQUEST_PERMISSION_CODE);
        }
    }

    /**
     * 权限申请的回调
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        doNext(requestCode,grantResults);
    }

    /**
     * 权限的处理
     * @param requestCode
     * @param grantResults
     */
    private void doNext(int requestCode, int[] grantResults) {
        if (requestCode == REQUEST_PERMISSION_CODE) {
            
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted     同意
                initLocation();

            } else {
                // Permission Denied       拒绝
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("权限申请")
                        .setMessage("在设置-应用-权限中开始读写权限，以保证功能的正常使用")
                        .setPositiveButton("去开启", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", getPackageName(), null);
                                intent.setData(uri);
                                startActivity(intent);

                                dialog.dismiss();
                            }
                        })
                        .setNegativeButton("取消", null)
                        .setCancelable(false)
                        .show();
            }
        }
    }

}
